package errcode

import (
	"fmt"
)

type Error struct {
	ErrorCode    int      `json:"code"`
	ErrorMsg     string   `json:"msg"`
	ErrorDetails []string `json:"details"`
}

var codes = map[int]string{}

func NewError(code int, msg string) *Error {
	if _, ok := codes[code]; ok {
		panic(fmt.Sprintf("错误码 %d 已经存在，请更换一个", code))
	}
	codes[code] = msg
	return &Error{ErrorCode: code, ErrorMsg: msg}
}

func (e *Error) Error() string {
	return fmt.Sprintf("错误码：%d, 错误信息：%s", e.Code(), e.Msg())
}

func (e *Error) Code() int {
	return e.ErrorCode
}

func (e *Error) Msg() string {
	return e.ErrorMsg
}

func (e *Error) Msgf(args []interface{}) string {
	return fmt.Sprintf(e.ErrorMsg, args...)
}

func (e *Error) Details() []string {
	return e.ErrorDetails
}

func (e *Error) WithDetails(details ...string) *Error {
	newError := *e
	newError.ErrorDetails = []string{}
	for _, d := range details {
		newError.ErrorDetails = append(newError.ErrorDetails, d)
	}
	return &newError
}
